package com.xmy.pc;

/**
 * Synchronized锁实现生产者消费者问题
 */
public class A {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.decrement();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.increment();
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.decrement();
            }
        },"D").start();
    }
}


class Data{
    private int number=0;
    public synchronized void increment(){
        if (number!=0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"+1完毕，当前值=>"+number);
        //通知其他线程，我+1完毕了
        this.notifyAll();
    }

    public synchronized void decrement(){
        if (number==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"-1完毕，当前值=>"+number);
        this.notifyAll();
    }
}


